package com.kahriboo.log4mon.appender;

import org.apache.log4j.spi.LoggingEvent;

import com.kahriboo.log4mon.data.LogEventProtos.LogEvent;
import com.kahriboo.log4mon.data.LogEventProtos.LogEvent.StackTrace;

public class LogEventFactory {

	/**
	 * Create a GoogleProtocolBuffer LogEvent usign a Log4J LoggingEvent
	 * 
	 * @param event the source
	 * @return the GoogleProtocolBuffer LogEvent
	 */
	public static LogEvent createFrom(final LoggingEvent event) {
		// LogEvent builder (because LogEvent is immuable)
		LogEvent.Builder result = LogEvent.newBuilder();

		// LEVEL info
		result = result.setLevel(event.getLevel().toInt());

		// LOCATION infos (optional)
		if (event.getLocationInformation() != null) {
			final String className = event.getLocationInformation().getClassName();
			final String methodName = event.getLocationInformation().getMethodName();
			final String fileName = event.getLocationInformation().getFileName();
			final String lineNumber = event.getLocationInformation().getLineNumber();
			result = result.setClassName(className);
			result = result.setMethodName(methodName);
			result = result.setFileName(fileName);
			result = result.setLineNumber(lineNumber);
		}

		// LOGGERNAME info
		result = result.setLoggerName(event.getLoggerName());

		// MESSAGE info (optional)
		if (event.getMessage() != null) {
			result = result.setMessage(event.getMessage().toString());
		}

		// THREADNAME info
		result = result.setThreadName(event.getThreadName());

		// THROWABLE infos (optional)
		if (event.getThrowableInformation() != null) {
			final String[] throwable = event.getThrowableInformation().getThrowableStrRep();
			final String throwableClass = event.getThrowableInformation().getThrowable().getClass().getName();

			final StackTrace.Builder stackResult = StackTrace.newBuilder();
			for (final String line : throwable) {
				stackResult.addLine(line);
			}

			result = result.setThrowable(stackResult);
			result = result.setThrowableClass(throwableClass);
		}

		// TIMESTAMP info
		result = result.setTimeStamp(event.getTimeStamp());

		// build the resulting object
		return result.build();
	}
}
